<template>
  <ArtTableFullScreen>
    <div id="table-full-screen" :style="{ height: containerMinHeight}">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="formFilters"
        :items="formItems"
		:showExpand="false"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card" style="height: calc(100vh - 214px);">
        <!-- 表格头部 -->
        <ArtTableHeader v-model:columns="columnChecks" @refresh="handleRefresh">
          <template #left>
            <ElButton @click="showDialog('add')">新增角色</ElButton>
          </template>
        </ArtTableHeader>

		<div style="height: calc(100% - 35px);">
			<!-- 表格 -->
			<ArtTable
			  ref="tableRef"
			  row-key="id"
			  :loading="loading"
			  :data="tableData"
			  :currentPage="pagination.currentPage"
			  :pageSize="pagination.pageSize"
			  :total="pagination.total"
			  :marginTop="10"
			  paginationAlign="right"
			  @selection-change="handleSelectionChange"
			  @size-change="handleSizeChange"
			  @current-change="handleCurrentChange"
			>
			  <template #default>
				<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
			  </template>
			</ArtTable>
		</div>
        <ElDialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
          width="30%"
          align-center
        >
          <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
            <ElFormItem label="中文名称" prop="cnName">
              <ElInput v-model="form.cnName" />
            </ElFormItem>
        	<ElFormItem label="英文名称" prop="enName">
        	  <ElInput v-model="form.enName" />
        	</ElFormItem>
            <ElFormItem label="角色编码" prop="code">
              <ElInput v-model="form.code" />
            </ElFormItem>
            <ElFormItem label="描述" prop="remark">
              <ElInput v-model="form.remark" type="textarea" :rows="3" />
            </ElFormItem>
            <ElFormItem label="启用">
              <ElSwitch v-model="form.enabled" active-value="0" inactive-value="1" />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="dialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleSubmit()">提交</ElButton>
            </div>
          </template>
        </ElDialog>
		
		<!--菜单授权a-->
		<ElDialog
		  v-model="permissionDialog"
		  title="菜单权限"
		  width="520px"
		  align-center
		  class="el-dialog-border"
		>
		  <ElScrollbar height="70vh">
		    <ElTree
		      ref="treeRef"
		      :data="processedMenuList"
		      show-checkbox
		      node-key="id"
		      :default-expand-all="isExpandAll"
		      :default-checked-keys="defaultCheckedKeys"
			  :check-strictly='true'
		      :props="defaultProps"
		      @check="handleTreeCheck"
		    >
		      <template #default="{ data }">
		        <div style="display: flex; align-items: center">
		          <span v-if="data.isAuth">
		            {{ data.label }}
		          </span>
		          <span v-else>{{ defaultProps.label(data) }}</span>
		        </div>
		      </template>
		    </ElTree>
		  </ElScrollbar>
		  <template #footer>
		    <div class="dialog-footer">
		      <ElButton @click="toggleExpandAll">{{ isExpandAll ? '全部收起' : '全部展开' }}</ElButton>
		      <ElButton @click="toggleSelectAll" style="margin-left: 8px">{{
		        isSelectAll ? '取消全选' : '全部选择'
		      }}</ElButton>
		      <ElButton type="primary" @click="savePermission">保存</ElButton>
		    </div>
		  </template>
		</ElDialog>
		
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElDialog, FormInstance, ElTag } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { SearchChangeParams, SearchFormItem } from '@/types'
  import dayjs from 'dayjs';
  import { RoleService } from '@/api/sys/roleApi'
  import { MenuService } from '@/api/menuApi'
  import { useMenuStore } from '@/store/modules/menu'
  import { useCommon } from '@/composables/useCommon'
  import { useI18n } from 'vue-i18n'
  defineOptions({ name: 'Role' }) // 定义组件名称，用于 KeepAlive 缓存控制
  const { containerMinHeight } = useCommon()
  const { locale } = useI18n()
  const { width } = useWindowSize()
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const { menuList } = storeToRefs(useMenuStore())

  // 定义表单搜索初始值
  const initialSearchState = {
    cnName: '',
    enName: '',
    enabled: '',
	isDel:0
  }

  const roleList = ref<any[]>([])

  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 表格数据
  const tableData = ref<any[]>([])

  // 表格实例引用
  const tableRef = ref()

  // 选中的行数据
  const selectedRows = ref<any[]>([])

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    pagination.currentPage = 1 // 重置到第一页
    getRoleList()
  }

  // 搜索处理
  const handleSearch = () => {
    console.log('搜索参数:', formFilters)
    pagination.currentPage = 1 // 搜索时重置到第一页
    getRoleList()
  }

  // 表单项变更处理
  const handleFormChange = (params: SearchChangeParams): void => {
    console.log('表单项变更:', params)
  }

  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '中文名称',
      prop: 'cnName',
      type: 'input',
      config: {
        clearable: true
      },
      onChange: handleFormChange
    },

    {
      label: '英文名称',
      prop: 'enName',
      type: 'input',
      config: {
        clearable: true
      },
      onChange: handleFormChange
    },
    {
      label: '状态',
      prop: 'enabled',
      type: 'select',
      config: {
        clearable: true
      },
      options: () => [
        { label: '全部', value: '' },
        { label: '启用', value: '0' },
        { label: '禁用', value: '1' }
      ],
      onChange: handleFormChange
    }
  ]

  const getTagType = (status: string) => {
    switch (status) {
      case '0':
        return 'success'
      case '1':
        return 'danger'
      default:
        return 'danger'
    }
  }

  // 构建标签文本
  const buildTagText = (status: string) => {
    let text = ''
    if (status === '0') {
      text = '启用'
    } else if (status === '1') {
      text = '禁用'
    }else{
		text = '未知'
	}
    return text
  }

  // 显示对话框
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
	  form.id = row.id
      form.cnName = row.cnName
	  form.enName = row.enName
      form.code = row.code
      form.remark = row.remark
      form.enabled = row.enabled
    } else {
      form.cnName = ''
	  form.enName = ''
      form.code = ''
      form.remark = ''
      form.enabled = 0
    }
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
	{ prop: 'cnName', label: '中文名称' },
	{ prop: 'enName', label: '英文名称' },
    { prop: 'code', label: '编码' },
	{ prop: 'remark', label: '描述' },
    {
      prop: 'enabled',
      label: '状态',
      formatter: (row: { enabled: string }) => {
        return h(ElTag, { type: getTagType(row.enabled) }, () => buildTagText(row.enabled))
      }
    },
    {
      prop: 'modifyTime',
      label: '编辑时间',
      formatter: (row:any) => {
      		return dayjs(row.modifyTime).format('YYYY-MM-DD HH:MM:ss')
      }
    },
    {
      prop: 'operation',
      label: '操作',
      width: 200,
      // fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', [
			h(ArtButtonTable, {
				type: 'edit',
				icon:'&#xe740;',
				iconColor:'#5D87FF',
				onClick: () => showPermissionDialog(row)
			}),
			h(ArtButtonTable, {
				type: 'edit',
				onClick: () => showDialog('edit', row)
			}),
			h(ArtButtonTable, {
				type: 'delete',
				onClick: () => deleteRole(row)
			})
        ])
      }
    }
  ])

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const form = reactive({
	id:'',
	cnName: '',
	enName: '',
	code: '',
	remark: '',
	enabled: 0
  })

  onMounted(() => {
    getRoleList()
  })

  const getRoleList = async () => {
    loading.value = true
    try {
      const { list, pageNumber, pageSize, totalRow } = await RoleService.pages({
        pageNumber: pagination.currentPage,
        pageSize:pagination.pageSize,
		query:formFilters
      })
      tableData.value = list;
      Object.assign(pagination, { 
		  currentPage: pageNumber,
		   pageSize: pageSize, 
		   totalRow ,
	  })
    } catch (error) {
      console.error('获取角色列表失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  const deleteRole =  (row:any) => {
    ElMessageBox.confirm('确定删除该角色吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
		loading.value = true
  		try {
  			await RoleService.delete(row.id);
  			loading.value = false
  			 ElMessage.success('删除成功')
  			getRoleList();
  		} catch {
  			ElMessage.error(`失败`)
  		}finally{
			dialogVisible.value = false
		}
    })
  }

  const handleRefresh = () => {
    getRoleList()
  }

  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }

  // 表单验证规则
  const rules = reactive<FormRules>({
    cnName: [
      { required: true, message: '请输入角色中文名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
	enName: [
	  { required: true, message: '请输入角色英文名称', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
	code: [
	  { required: true, message: '请输入角色标识', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
    remark: [{ min: 0, max: 250, message: '最大长度250 个字符', trigger: 'blur' }]
  })

  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
		loading.value = true
        try {
  			await RoleService.save(form);
			const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
			ElMessage.success(message)
  			getRoleList();
        } catch {
  			ElMessage.error(`失败`)
        }finally{
			dialogVisible.value = false
			loading.value = false
		}
      }
    })
  }

  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getRoleList()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.currentPage = newCurrentPage
    getRoleList()
  }
  
  const permissionDialog = ref(false)
  const treeRef = ref()
  const isExpandAll = ref(true)
  const isSelectAll = ref(false)
  const defaultProps = {
    children: 'children',
    label: (data: any) => formatMenuTitle(data) || ''
  }
  const defaultCheckedKeys=ref<string[]>();
  const processedMenuList=ref<any[]>([]);
  
  // const processedMenuList = computed(() => {
  //   const processNode = (node: any) => {
  //     const processed = { ...node }
  //     // 如果有 authList，将其转换为子节点
  //     if (node.meta && node.meta.authList && node.meta.authList.length) {
  //       const authNodes = node.meta.authList.map((auth: any) => ({
  //         id: `${auth.id}`,
  //         name: formatMenuTitle(auth),
  //         label: formatMenuTitle(auth),
  //         auth_mark: auth.auth_mark,
  //         isAuth: true,
  //         checked: auth.checked || false
  //       }))
  
  //       processed.children = processed.children ? [...processed.children, ...authNodes] : authNodes
  //     }
  
  //     // 递归处理子节点
  //     if (processed.children) {
  //       processed.children = processed.children.map(processNode)
  //     }
  
  //     return processed
  //   }
  //   return menuList.value.map(processNode)
  // })
  
  const authRole=ref<string>('');
  const showPermissionDialog= async (row:any)=>{
	  loading.value = true
	  try {
		defaultCheckedKeys.value = await RoleService.menus(row.id);
		
		const data = await MenuService.getLoadAll({
			query:{
				isDel:0
			}
		});
		
		processedMenuList.value=data;
		
		
		authRole.value=row.id;
		permissionDialog.value=true;
	  } catch (error) {
	    console.error('获取角色拥有菜单Id集合失败:', error)
	  } finally {
	    loading.value = false
	  }
  }
  const toggleExpandAll = () => {
    const tree = treeRef.value
    if (!tree) return
    // 使用store.nodesMap直接控制所有节点的展开状态
    const nodes = tree.store.nodesMap
    for (const node in nodes) {
      nodes[node].expanded = !isExpandAll.value
    }
    isExpandAll.value = !isExpandAll.value
  }
  
  const handleTreeCheck = () => {
    const tree = treeRef.value
    if (!tree) return
  
    // 使用树组件的getCheckedKeys方法获取选中的节点
    const checkedKeys = tree.getCheckedKeys()
    const allKeys = getAllNodeKeys(processedMenuList.value)
  
    // 判断是否全选：选中的节点数量等于总节点数量
    isSelectAll.value = checkedKeys.length === allKeys.length && allKeys.length > 0
  }
  
  const getAllNodeKeys = (nodes: any[]): string[] => {
    const keys: string[] = []
    const traverse = (nodeList: any[]) => {
      nodeList.forEach((node) => {
        if (node.name) {
          keys.push(node.name)
        }
        if (node.children && node.children.length > 0) {
          traverse(node.children)
        }
      })
    }
    traverse(nodes)
    return keys
  }
  
  const toggleSelectAll = () => {
    const tree = treeRef.value
    if (!tree) return
  
    if (!isSelectAll.value) {
      // 全选：获取所有节点的key并设置为选中
      const allKeys = getAllNodeKeys(processedMenuList.value)
      tree.setCheckedKeys(allKeys)
    } else {
      // 取消全选：清空所有选中
      tree.setCheckedKeys([])
    }
    isSelectAll.value = !isSelectAll.value
  }
  
  const formatMenuTitle=(menu:any)=>{
  	  if(menu){
  		  return locale.value=='zh'?menu.cnName:menu.enName;
  	  }
  	  return '';
  }
  
const savePermission = async () => {
  // 1. 添加前置校验
  if (!authRole.value) {
    ElMessage.warning('请先选择角色');
    return;
  }
  
  const tree = treeRef.value;
  if (!tree) {
    ElMessage.error('菜单树未初始化');
    return;
  }
  
  // 2. 优化获取选中键的逻辑
  try {
    loading.value = true;
    
    // 3. 修复方法调用问题（移除 .json() 错误用法）
    const checkedKeys = tree.getCheckedKeys();
    
    // 4. 添加空值处理（根据后端需求）
    const menuIds = checkedKeys.length > 0 ? checkedKeys : [];
    
    // 5. 添加请求参数校验
    await RoleService.saveMenuIds(authRole.value, menuIds);
    
    // 6. 增强成功反馈
    ElMessage.success({
      message: `权限保存成功，更新了 ${menuIds.length} 个菜单`,
      duration: 3000
    });
    
    // 7. 重置状态
    authRole.value = '';
	permissionDialog.value=false;
	defaultCheckedKeys.value=[]
    
    // 8. 可选：清空树选择（根据业务需求）
    // tree.setCheckedKeys([]);
  } catch (error:any) {
    // 9. 增强错误处理
    console.error('权限保存失败:', error);
    ElMessage.error({
      message: `权限保存失败: ${error.message || '请稍后重试'}`,
      duration: 5000
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
</style>
